<template>
  <el-dialog
    title="初始化方法配置"
    :close-on-click-modal="false"
    width="50%"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="divisordataForm"
      @keyup.enter.native="dataFormSubmit()"
       label-width="120px"
    >
      <div class="row">
        <el-form-item label="类型" prop="actionMethodType" class="col-md-6">
          <el-select
            :disabled="isView"
            style="width: 200px"
            v-model="dataForm.actionMethodType"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="t in actionMethodTeam"
              :key="t.value"
              :label="t.label"
              :value="t.value"
              @click.native.prevent="changeMethodTeam(t)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方法" prop="qualityType" class="col-md-6">
          <el-select
            :disabled="isView"
            style="width: 200px"
            v-model="dataForm.qualityType"
            filterable
            clearable
            placeholder="请选择"
            @click.native.prevent="changemethod()"
          >
            <el-option
              v-for="item in entityItemType"
              :key="item.value"
              :label="item.label"
              :value="item.label"
              @click.native.prevent="changeitemName(item)"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="row">
        <el-form-item  v-if="dataForm.params && dataForm.params.length" label="参数" class="col-md-12">
            <el-select v-for="(itemsub,index) in dataForm.params" :key="index"
              :disabled="isView"
              style="width: 200px"
              v-model="dataForm.params[index].className"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="items in itemNames"
                :key="items.value"
                :label="items.label"
                :value="items.value"
                @click.native="changeMethodParams(items)"
              >
              </el-option>
            </el-select>
          </el-form-item>
      </div>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="!isView" :plain="true" type="info" @click="dataFormSubmit()">确定</el-button>
      <el-button @click="visible = false">返回</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getmethods } from "@/api/baseConfig/entity";
// 条件方法
// 动作方法
import {getEntityMethod,getActionMethodName} from '@/api/baseConfig/entity'
import { saveData, getData } from "@/api/baseConfig/divisor";
import constant from "../../../../../api/constant";
import bus from '../../../../../busEvent'

export default {
  data() {
    var validateIdentify = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("标识不能为空"));
      } else {
        var patrn = /^[a-z][a-zA-Z0-9]{0,50}$/;
        // console.log(value);
        if (!patrn.test(value)) {
          callback(new Error("标识由字母和数字组成，且首字母为小写长度小于50"));
        } else {
          callback();
        }
      }
    };
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("名称不能为空"));
      } else {
        var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
        var regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;

        if (regEn.test(value) || regCn.test(value) || value.length >= 50) {
          callback(new Error("名称不能包含特殊字符，且长度小于50"));
        } else {
          callback();
        }
      }
    };

    return {
      actionMethodTeam:[
        {label:"条件",value:"1"},
      {label:"动作",value:"2"},
      ],
      isView: false,
      visible: false,
      dataForm: {
        entityId: null,
        qualityType: "",
        itemId: null,
        methodName:'',
        actionMethodType: '',
          params:[],
      },
      entityItemType: {},
      dataRule: {
        qualityName: [{ validator: validateName, trigger: "blur" }],
        qualityIdentify: [{ validator: validateIdentify, trigger: "blur" }],
        actionMethodType: { required: true, message: '请选择类型', trigger: 'blur' },
        // qualityType: { required: true, message: '请选择方法', trigger: 'blur' },
      },
    };
  },
  props: {
    itemNames: Array,
    pzIndex: Number,
  },
  created() {
    // this.getmethodsData({});
    if (this.$route.query.isView) {
      this.isView = this.$route.query.isView;
    }
     bus.$on('actionInfo',(msg) => {
       // console.log(msg.actionInfo,'msg');
      this.dataForm= msg.actionInfo
    })

  },
  methods: {
    changemethod() {
      // console.log('222');
      if (this.dataForm.actionMethodType == '') {
       this.$refs["divisordataForm"].validateField("actionMethodType");  
       return
      }
    },
    changeMethodParams(item) {
      // console.log(item,'222');
      // this.dataForm[index] = item.value
    },
    changeitemName(str) {
      // console.log(str);
      this.dataForm.methodName = str.value;
      this.dataForm.params = str.params
      // console.log( this.dataForm.params,'222');
    },
    // 根据条件、动作筛选方法
    changeMethodTeam(item) {
      // console.log(item,this.dataForm);
      this.dataForm.actionMethodType = item.value
      this.entityItemType = {}
      if (item.value == '1') {
        // 条件
        if (this.dataForm.entityId) {    
          this.$store.dispatch("loading/CHANGE_LOADING", true);
           getEntityMethod({id:String(this.dataForm.entityId)}).then(res => {
         this.$store.dispatch("loading/CHANGE_LOADING", false);
             if (res.data.data) {
             let list = res.data.data;
             list.forEach((ele, index) => {
               ele.label = ele.className;
               ele.value = ele.name;
             });
             this.entityItemType = list;
             // console.log(this.entityItemType);
           }
      })
        } else {
          this.$message.error("条件方法未关联模型，无法获取方法！");
        }
        
      }else {
        // console.log(this.dataForm);
        // 动作
         this.$store.dispatch("loading/CHANGE_LOADING", true);
      getActionMethodName({id:String(this.dataForm.entityId)}).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
                if (res.data.data) {
            let list = res.data.data;
            list.forEach((ele, index) => {
              ele.label = ele.className;
              ele.value = ele.name;
            });
            this.entityItemType = list;
            // console.log(this.entityItemType);
          }
  })
      }
    },
    // 获取方法名称
    // getmethodsData(param) {
    //   this.$store.dispatch("loading/CHANGE_LOADING", true);
    //   getmethods(param)
    //     .then((res) => {
    //       this.$store.dispatch("loading/CHANGE_LOADING", false);
    //       // console.log(res);
    //       if (res.data.data) {
    //         let list = res.data.data;
    //         list.forEach((ele, index) => {
    //           ele.label = ele.className;
    //           ele.value = ele.name;
    //         });
    //         this.entityItemType = list;
    //         // console.log(this.entityItemType);
    //       }
    //     })
    //     .catch((err) => {
    //       this.$store.dispatch("loading/CHANGE_LOADING", false);
    //     });
    // },
    //初始化
    init(id) {
      this.dataForm = {
        qualityId: null,
        qualityName: "",
        qualityIdentify: "",
        qualityType: "",
        isEffect: "1",
        params:[],
        actionMethodType: '',
        entityId: null,
      };
      this.visible = true;

      this.$nextTick(() => {
        this.$refs["divisordataForm"].resetFields();
        if (id) {
          this.dataForm.qualityId = id;
          let params = {
            id: this.dataForm.qualityId + "",
          };
        }
      });
    },


    // 表单提交
    dataFormSubmit() {
      this.$refs["divisordataForm"].validate((valid) => {
        if (valid) {
          // console.log(this.dataForm);
          // this.dataForm.actionName = this.dataForm.actionDesc = this.dataForm.qualityType
          let actionList = {
            entityId: null,
            actionId: this.dataForm.actionId || null,
            actionName: this.dataForm.qualityType,
            actionDesc: this.dataForm.qualityType,
            itemId: null,
            methodName: this.dataForm.methodName,
            methodParams: this.dataForm.params,
            actionMethodType:this.dataForm.actionMethodType
          };
          let obj1 = {
            actionList: actionList,
            pzIndex: this.pzIndex,
          };
          this.$emit("actionList", obj1);
          this.visible = false;
          // this.dataForm = {};
          // saveData(JSON.stringify(this.dataForm))
          //   .then((res) => {
          //     this.$store.dispatch("loading/CHANGE_LOADING", false);
          //     if (res.data && res.data.resultCode === 0) {
          //       this.$message({
          //         message: "操作成功",
          //         type: "success",
          //         duration: 1500,
          //         onClose: () => {
          //           this.visible = false;
          //           this.dataForm = {
          //             qualityId: null,
          //             qualityIdentify: "",
          //             qualityName: "",
          //             qualityType: "",
          //             isEffect: "1",
          //           };
          //           this.$emit("refreshDataList");
          //         },
          //       });
          //     } else {
          //       this.$message.error(res.data.resultMsg);
          //     }
          //   })
          //   .catch((err) => {
          //     this.$store.dispatch("loading/CHANGE_LOADING", false);
          //   });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.title {
  padding: 10px;
  background-color: rgba(248, 248, 248, 1);
  margin-bottom: 10px;
}

.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}
.el-dialog__body .el-col-20 .el-form-item .el-form-item__content {
  display: flex !important;
}
</style>
